package zz.demo.springCloud.wechat.controller;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zz.demo.springCloud.wechat.config.WxCpServiceAdapter;
import zz.demo.springCloud.wechat.config.WxOperations;
import zz.demo.springCloud.wechat.entity.WeChatApp;

import java.util.List;

/**
 * Created by zhangzheng on 2017-11-9.
 */
@RestController
@RequestMapping("/wechat/main")
public class WxMainController {
    @Autowired
    private WxOperations wxOperations;

    private static final String HTTP_FRONT = "http://mp.original-tech.cn" ;

    @PostMapping("/updateApp")
    public String updateApp(WeChatApp weChatApp){
        return "OK";
    }

    @PostMapping("/getUser")
    public WxCpUser user(){
        WxCpUser wxCpUser = new WxCpUser();
        wxCpUser.setName("zhangsan");
        return wxCpUser;
    }

    @PostMapping("/menuCreate/{agentId}")
    public String wxMenu(@PathVariable("agentId") Integer agentId,@RequestBody WxMenu wxMenu){
        WxCpServiceAdapter wxCpService = wxOperations.findByAgentId(agentId);
        if(wxCpService== null){
            return "error";
        }
        List<WxMenuButton> wxMenuButtonList = wxMenu.getButtons();
        for(WxMenuButton button :wxMenuButtonList){
            if(WxConsts.BUTTON_VIEW.equals(button.getType())){
                button.setUrl(wxCpService.getOauth2Service().buildAuthorizationUrl(HTTP_FRONT + button.getUrl(),
                        "chart"));
            }
        }
        try {
            wxCpService.getMenuService().create(wxMenu);
            return "OK";
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "error";
    }

}
